#include "datasave.h"

#include <QDateTime>
#include <QDebug>
#include <QIODevice>
#include <QString>
#include <QThread>

#include "mainwindow.h"

DataSave::DataSave(QObject* parent) : QObject{parent} { save_flag = false; }

DataSave::~DataSave() {}

void DataSave::SaveOpen() {
    qDebug() << "FileOpen" << QThread::currentThread();
    QDateTime time = QDateTime::currentDateTime();
    // 将时间对面按照一定的格式转换为字符串对象
    QString str = time.toString("yyMMdd-hhmmss");
    QString FileName = "SaveFile-" + str + ".csv";

    saveFile.setFileName(FileName);
    // 如果打开失败则返回退出
    if (!saveFile.open(QIODevice::WriteOnly | QIODevice::Text)) {
        qDebug() << "file: " + FileName + " not create";
        emit sig_fileNotOpen();
        return;
    }
    qDebug() << "file: " + FileName + " create";
    emit sig_fileIsOpen();
}

void DataSave::SaveClose() {
    qDebug() << "FileClose" << QThread::currentThread();
    save_flag = false;
    if (saveFile.isOpen()) {
        saveFile.close();
    }
}

void DataSave::do_CloseFile() { SaveClose(); }

void DataSave::do_rcv_save(QByteArray data) {
    if (stamp_flag) {
        QDateTime time = QDateTime::currentDateTime();
        // 将时间对面按照一定的格式转换为字符串对象
        QString str = time.toString("hhmmsszzz,");
        QByteArray stamp = str.toLatin1();
        data = stamp + data;
    }
    // QString save_str;
    if (save_flag) {
        // save_str = QString(data);
        saveFile.write(data);
        // qDebug() << QByteArray::fromHex(QByteArray::number(data, 16));
        qDebug() << "write data:" << QString(data);
    }
}

void DataSave::do_setSaveFlag(bool flag) {
    save_flag = flag;
    SaveOpen();
}

void DataSave::do_setStampFlag(bool flag) {
    stamp_flag = flag;
    qDebug() << "实际没什么用，可以直接在写文件前入去ckeck值";
}
